<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js" lang="en">
<!--<![endif]-->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Row Counts - The .NET Core ORM Cookbook</title>
    <link rel="shortcut icon" href="favicon.ico">
    <link rel="stylesheet" href="css/theme.css" type="text/css" />
    <link rel="stylesheet" href="css/theme_colors.css" type="text/css" />
    <link rel="stylesheet" href="css/styles/vs.css">
    <link rel="stylesheet" href="css/font-awesome.4.5.0.min.css">
</head>
<body role="document">
    <div class="grid-for-nav">
        <nav data-toggle="nav-shift" class="nav-side stickynav">
            <div class="side-nav-search">
                <a href="index.htm"><i class="fa fa-home"></i> The .NET Core ORM Cookbook</a>
                <div role="search">
                    <form id="search-form" class="form" action="Docnet_search.htm" method="get">
                        <input type="text" name="q" placeholder="Search docs" />
                    </form>
                </div>
            </div>
            <div class="menu menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<ul>
<li class="tocentry"><a href="index.htm">Home</a>
</li>

<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="ORMs.htm">ORMs</a></span>
</li>
<li class="tocentry"><a href="FAQ.htm">FAQ</a>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="StandardCRUDscenarios.htm">Standard CRUD scenarios</a></span>
</li>
<li class="tocentry">
<ul>
<li><span class="navigationgroup"><i class="fa fa-caret-down"></i> <a href="Fetchingdatascenarios.htm">Fetching data scenarios</a></span></li>
<li class="tocentry"><a href="Joins.htm">Projecting with a Join</a>
</li>
<li class="tocentry"><a href="Views.htm">Reading from Views</a>
</li>
<li class="tocentry current"><a class="current" href="RowCount.htm">Row Counts</a>
<ul class="currentrelative">
<li class="tocentry"><a href="#scenario-prototype">Scenario Prototype</a></li>

<li class="tocentry"><a href="#ado.net">ADO.NET</a></li>

<li class="tocentry"><a href="#chain">Chain</a></li>

<li class="tocentry"><a href="#dapper">Dapper</a></li>

<li class="tocentry"><a href="#dbconnector">DbConnector</a></li>

<li class="tocentry"><a href="#entity-framework-6">Entity Framework 6</a></li>

<li class="tocentry"><a href="#entity-framework-core">Entity Framework Core</a></li>

<li class="tocentry"><a href="#linq-to-db">LINQ to DB</a></li>

<li class="tocentry"><a href="#llblgen-pro">LLBLGen Pro</a></li>

<li class="tocentry"><a href="#nhibernate">NHibernate</a></li>

<li class="tocentry"><a href="#repodb">RepoDb</a></li>

<li class="tocentry"><a href="#servicestack">ServiceStack</a></li>



</ul>
<li class="tocentry"><a href="Pagination.htm">Paging Results</a>
</li>
<li class="tocentry"><a href="PopulateDataTable.htm">Populate DataTable</a>
</li>
<li class="tocentry"><a href="ScalarValue.htm">Reading a Salar Value from a Row</a>
</li>
<li class="tocentry"><a href="SingleColumn.htm">Reading a Single Column from a Table</a>
</li>

</ul>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="Advancedscenarios.htm">Advanced scenarios</a></span>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="Sortingscenarios.htm">Sorting scenarios</a></span>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="Storedprocedurescenarios.htm">Stored procedure scenarios</a></span>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="Auditingandhistoryscenarios.htm">Auditing and history scenarios</a></span>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="Multi-Tenancyscenarios.htm">Multi-Tenancy scenarios</a></span>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="UnknownDatabasescenarios.htm">Unknown Database scenarios</a></span>
</li>
</ul>
				<div class="toc-footer">
					<span class="text-small">
						<hr/>
						<a href="https://github.com/FransBouma/DocNet" target="_blank">Made with <i class="fa fa-github"></i> DocNet</a>
					</span>
				</div>	
			</div>
            &nbsp;
        </nav>
        <section data-toggle="nav-shift" class="nav-content-wrap">
            <nav class="nav-top" role="navigation" aria-label="top navigation">
                <i data-toggle="nav-top" class="fa fa-bars"></i>
                <a href="index.htm">The .NET Core ORM Cookbook</a>
            </nav>
            <div class="nav-content">
                <div role="navigation" aria-label="breadcrumbs navigation">
                    <div class="breadcrumbs">
<ul><li><a href="index.htm">Home</a></li> / <li><a href="Fetchingdatascenarios.htm">Fetching data scenarios</a></li> / <li><a href="RowCount.htm">Row Counts</a></li></ul>
					
                    </div>
                    <hr />
                </div>
                <div role="main">
                    <div class="section">
<h1 id="row-counts">Row Counts<a class="headerlink" href="#row-counts" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h1>
<p>These scenarios demonstrate how to get a row count from a table. </p>
<h2 id="scenario-prototype">Scenario Prototype<a class="headerlink" href="#scenario-prototype" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public interface IRowCountScenario&lt;TEmployeeSimple&gt;
   where TEmployeeSimple : class, IEmployeeSimple, new()
{
    /// &lt;summary&gt;
    /// Count of the employees, filtered by last name.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;lastName&quot;&gt;The last name.&lt;/param&gt;
    int EmployeeCount(string lastName);

    /// &lt;summary&gt;
    /// Count of the employees, filtered by last name.
    /// &lt;/summary&gt;
    int EmployeeCount();

    /// &lt;summary&gt;
    /// Insert a collection of Employee rows.
    /// &lt;/summary&gt;
    void InsertBatch(IList&lt;TEmployeeSimple&gt; employees);
}
</code></pre>

<h2 id="ado.net">ADO.NET<a class="headerlink" href="#ado.net" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<p>In ADO.NET, <code>ExecuteScalar</code> returns the first column of the first row in the resultset. Everything else is discarded.</p>
<pre><code class="cs">    public class RowCountScenario : SqlServerScenarioBase, IRowCountScenario&lt;EmployeeSimple&gt;
    {
        public RowCountScenario(string connectionString) : base(connectionString)
        { }

        public int EmployeeCount(string lastName)
        {
            const string sql = &quot;SELECT COUNT(*) FROM HR.Employee e WHERE e.LastName = @LastName&quot;;
            using (var con = OpenConnection())
            using (var cmd = new SqlCommand(sql, con))
            {
                cmd.Parameters.AddWithValue(&quot;@LastName&quot;, lastName);
                return (int)cmd.ExecuteScalar();
            }
        }

        public int EmployeeCount()
        {
            const string sql = &quot;SELECT COUNT(*) FROM HR.Employee e&quot;;
            using (var con = OpenConnection())
            using (var cmd = new SqlCommand(sql, con))
                return (int)cmd.ExecuteScalar();
        }

        public void InsertBatch(IList&lt;EmployeeSimple&gt; employees)
        {
            if (employees == null || employees.Count == 0)
                throw new ArgumentException($&quot;{nameof(employees)} is null or empty.&quot;, nameof(employees));

            var sql = new StringBuilder(@&quot;INSERT INTO HR.Employee
(FirstName, MiddleName, LastName, Title, OfficePhone, CellPhone, EmployeeClassificationKey)
VALUES &quot;);

            for (var i = 0; i &lt; employees.Count; i++)
            {
                if (i != 0)
                    sql.AppendLine(&quot;,&quot;);
                sql.Append($&quot;(@FirstName_{i}, @MiddleName_{i}, @LastName_{i}, @Title_{i}, @OfficePhone_{i}, @CellPhone_{i}, @EmployeeClassificationKey_{i})&quot;);
            }
            sql.AppendLine(&quot;;&quot;);

            using (var con = OpenConnection())
            using (var cmd = new SqlCommand(sql.ToString(), con))
            {
                for (var i = 0; i &lt; employees.Count; i++)
                {
                    cmd.Parameters.AddWithValue($&quot;@FirstName_{i}&quot;, employees[i].FirstName);
                    cmd.Parameters.AddWithValue($&quot;@MiddleName_{i}&quot;, (object?)employees[i].MiddleName ?? DBNull.Value);
                    cmd.Parameters.AddWithValue($&quot;@LastName_{i}&quot;, employees[i].LastName);
                    cmd.Parameters.AddWithValue($&quot;@Title_{i}&quot;, (object?)employees[i].Title ?? DBNull.Value);
                    cmd.Parameters.AddWithValue($&quot;@OfficePhone_{i}&quot;, (object?)employees[i].OfficePhone ?? DBNull.Value);
                    cmd.Parameters.AddWithValue($&quot;@CellPhone_{i}&quot;, (object?)employees[i].CellPhone ?? DBNull.Value);
                    cmd.Parameters.AddWithValue($&quot;@EmployeeClassificationKey_{i}&quot;, employees[i].EmployeeClassificationKey);
                }
                cmd.ExecuteNonQuery();
            }
        }
    }
</code></pre>

<h2 id="chain">Chain<a class="headerlink" href="#chain" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public class RowCountScenario : IRowCountScenario&lt;EmployeeSimple&gt;
{
    readonly SqlServerDataSource m_DataSource;

    public RowCountScenario(SqlServerDataSource dataSource)
    {
        m_DataSource = dataSource;
    }

    public int EmployeeCount(string lastName)
    {
        return (int)m_DataSource.From&lt;EmployeeSimple&gt;(new { lastName }).AsCount().Execute();
    }

    public int EmployeeCount()
    {
        return (int)m_DataSource.From&lt;EmployeeSimple&gt;().AsCount().Execute();
    }

    public void InsertBatch(IList&lt;EmployeeSimple&gt; employees)
    {
        if (employees == null || employees.Count == 0)
            throw new ArgumentException($&quot;{nameof(employees)} is null or empty.&quot;, nameof(employees));

        m_DataSource.InsertBatch((IReadOnlyList&lt;EmployeeSimple&gt;)employees).Execute();
    }
}
</code></pre>

<h2 id="dapper">Dapper<a class="headerlink" href="#dapper" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">    public class RowCountScenario : ScenarioBase, IRowCountScenario&lt;EmployeeSimple&gt;
    {
        public RowCountScenario(string connectionString) : base(connectionString)
        { }

        public int EmployeeCount(string lastName)
        {
            const string sql = &quot;SELECT COUNT(*) FROM HR.Employee e WHERE e.LastName = @LastName&quot;;
            using (var con = OpenConnection())
                return con.ExecuteScalar&lt;int&gt;(sql, new { lastName });
        }

        public int EmployeeCount()
        {
            const string sql = &quot;SELECT COUNT(*) FROM HR.Employee e&quot;;
            using (var con = OpenConnection())
                return con.ExecuteScalar&lt;int&gt;(sql);
        }

        public void InsertBatch(IList&lt;EmployeeSimple&gt; employees)
        {
            if (employees == null || employees.Count == 0)
                throw new ArgumentException($&quot;{nameof(employees)} is null or empty.&quot;, nameof(employees));

            const string sql = @&quot;INSERT INTO HR.Employee
(FirstName, MiddleName, LastName, Title, OfficePhone, CellPhone, EmployeeClassificationKey)
VALUES (@FirstName, @MiddleName, @LastName, @Title, @OfficePhone, @CellPhone, @EmployeeClassificationKey)&quot;;
            using (var con = OpenConnection())
                con.Execute(sql, employees);
        }
    }
</code></pre>

<h2 id="dbconnector">DbConnector<a class="headerlink" href="#dbconnector" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public class RowCountScenario : ScenarioBase, IRowCountScenario&lt;EmployeeSimple&gt;
{
    public RowCountScenario(string connectionString) : base(connectionString)
    { }

    public int EmployeeCount(string lastName)
    {
        const string sql = &quot;SELECT COUNT(*) FROM HR.Employee e WHERE e.LastName = @lastName&quot;;

        return DbConnector.Scalar&lt;int&gt;(sql, new { lastName }).Execute();
    }

    public int EmployeeCount()
    {
        const string sql = &quot;SELECT COUNT(*) FROM HR.Employee e&quot;;

        return DbConnector.Scalar&lt;int&gt;(sql).Execute();
    }

    public void InsertBatch(IList&lt;EmployeeSimple&gt; employees)
    {
        if (employees == null || employees.Count == 0)
            throw new ArgumentException($&quot;{nameof(employees)} is null or empty.&quot;, nameof(employees));

        //Best approach for unlimited inserts since SQL server has parameter amount restrictions
        //https://docs.microsoft.com/en-us/sql/sql-server/maximum-capacity-specifications-for-sql-server?redirectedfrom=MSDN&amp;view=sql-server-ver15
        DbConnector.Build&lt;int?&gt;(
                sql: @$&quot;INSERT INTO {EmployeeSimple.TableName}
                (
                    CellPhone,
                    EmployeeClassificationKey,
                    FirstName,
                    LastName,
                    MiddleName,
                    OfficePhone,
                    Title
                ) 
                VALUES (
                    @{nameof(EmployeeSimple.CellPhone)},
                    @{nameof(EmployeeSimple.EmployeeClassificationKey)},
                    @{nameof(EmployeeSimple.FirstName)},
                    @{nameof(EmployeeSimple.LastName)},
                    @{nameof(EmployeeSimple.MiddleName)},
                    @{nameof(EmployeeSimple.OfficePhone)},
                    @{nameof(EmployeeSimple.Title)}
                )&quot;,
                param: employees[0],
                onExecute: (int? result, IDbExecutionModel em) =&gt;
                {
                    //Set the command
                    DbCommand command = em.Command;

                    //Execute first row.
                    em.NumberOfRowsAffected = command.ExecuteNonQuery();

                    //Set and execute remaining rows.
                    for (int i = 1; i &lt; employees.Count; i++)
                    {
                        var emp = employees[i];

                        command.Parameters[nameof(EmployeeSimple.CellPhone)].Value = emp.CellPhone ?? (object)DBNull.Value;
                        command.Parameters[nameof(EmployeeSimple.EmployeeClassificationKey)].Value = emp.EmployeeClassificationKey;
                        command.Parameters[nameof(EmployeeSimple.FirstName)].Value = emp.FirstName ?? (object)DBNull.Value;
                        command.Parameters[nameof(EmployeeSimple.LastName)].Value = emp.LastName ?? (object)DBNull.Value;
                        command.Parameters[nameof(EmployeeSimple.MiddleName)].Value = emp.MiddleName ?? (object)DBNull.Value;
                        command.Parameters[nameof(EmployeeSimple.OfficePhone)].Value = emp.OfficePhone ?? (object)DBNull.Value;
                        command.Parameters[nameof(EmployeeSimple.Title)].Value = emp.Title ?? (object)DBNull.Value;

                        em.NumberOfRowsAffected += command.ExecuteNonQuery();
                    }

                    return em.NumberOfRowsAffected;
                }
            )
            .WithIsolationLevel(IsolationLevel.ReadCommitted)//Use a transaction
            .Execute();
    }
}
</code></pre>

<h2 id="entity-framework-6">Entity Framework 6<a class="headerlink" href="#entity-framework-6" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public class RowCountScenario : IRowCountScenario&lt;Employee&gt;
{
    private Func&lt;OrmCookbookContext&gt; CreateDbContext;

    public RowCountScenario(Func&lt;OrmCookbookContext&gt; dBContextFactory)
    {
        CreateDbContext = dBContextFactory;
    }

    public int EmployeeCount(string lastName)
    {
        using (var context = CreateDbContext())
            return context.Employee.Where(e =&gt; e.LastName == lastName).Count();
    }

    public int EmployeeCount()
    {
        using (var context = CreateDbContext())
            return context.Employee.Count();
    }

    public void InsertBatch(IList&lt;Employee&gt; employees)
    {
        using (var context = CreateDbContext())
        {
            context.Employee.AddRange(employees);
            context.SaveChanges();
        }
    }
}
</code></pre>

<h2 id="entity-framework-core">Entity Framework Core<a class="headerlink" href="#entity-framework-core" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public class RowCountScenario : IRowCountScenario&lt;Employee&gt;
{
    private Func&lt;OrmCookbookContext&gt; CreateDbContext;

    public RowCountScenario(Func&lt;OrmCookbookContext&gt; dBContextFactory)
    {
        CreateDbContext = dBContextFactory;
    }

    public int EmployeeCount(string lastName)
    {
        using (var context = CreateDbContext())
            return context.Employees.Where(e =&gt; e.LastName == lastName).Count();
    }

    public int EmployeeCount()
    {
        using (var context = CreateDbContext())
            return context.Employees.Count();
    }

    public void InsertBatch(IList&lt;Employee&gt; employees)
    {
        using (var context = CreateDbContext())
        {
            context.Employees.AddRange(employees);
            context.SaveChanges();
        }
    }
}
</code></pre>

<h2 id="linq-to-db">LINQ to DB<a class="headerlink" href="#linq-to-db" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public class RowCountScenario : IRowCountScenario&lt;Employee&gt;
{
    public int EmployeeCount(string lastName)
    {
        using (var db = new OrmCookbook())
            return db.Employee.Where(e =&gt; e.LastName == lastName).Count();
    }

    public int EmployeeCount()
    {
        using (var db = new OrmCookbook())
            return db.Employee.Count();
    }

    public void InsertBatch(IList&lt;Employee&gt; employees)
    {
        if (employees == null || employees.Count == 0)
            throw new ArgumentException($&quot;{nameof(employees)} is null or empty.&quot;, nameof(employees));

        using (var db = new OrmCookbook())
        {
            foreach (var employee in employees)
                db.Insert(employee);
        }
    }
}
</code></pre>

<h2 id="llblgen-pro">LLBLGen Pro<a class="headerlink" href="#llblgen-pro" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public class RowCountScenario : IRowCountScenario&lt;EmployeeEntity&gt;
{
    public int EmployeeCount(string lastName)
    {
        using(var adapter = new DataAccessAdapter())
        {
            return new LinqMetaData(adapter).Employee.Count(e =&gt; e.LastName == lastName);
        }
    }


    public int EmployeeCount()
    {
        using(var adapter = new DataAccessAdapter())
        {
            // Use queryspec for a change... 
            return adapter.FetchScalar&lt;int&gt;(new QueryFactory().Employee.Select(Functions.CountRow()));
        }
    }


    public void InsertBatch(IList&lt;EmployeeEntity&gt; employees)
    {
        using(var toInsert = new EntityCollection&lt;EmployeeEntity&gt;(employees))
        {
            using(var adapter = new DataAccessAdapter())
            {
                // 0 switches off batching
                adapter.BatchSize = employees?.Count ?? 0;
                adapter.SaveEntityCollection(toInsert);
            }
        }
    }
}
</code></pre>

<h2 id="nhibernate">NHibernate<a class="headerlink" href="#nhibernate" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public class RowCountScenario : IRowCountScenario&lt;Employee&gt;
{
    readonly ISessionFactory m_SessionFactory;

    public RowCountScenario(ISessionFactory sessionFactory)
    {
        m_SessionFactory = sessionFactory;
    }

    public int EmployeeCount(string lastName)
    {
        using (var session = m_SessionFactory.OpenSession())
            return session.Query&lt;Employee&gt;().Where(e =&gt; e.LastName == lastName).Count();
    }

    public int EmployeeCount()
    {
        using (var session = m_SessionFactory.OpenSession())
            return session.Query&lt;Employee&gt;().Count();
    }

    public void InsertBatch(IList&lt;Employee&gt; employees)
    {
        if (employees == null || employees.Count == 0)
            throw new ArgumentException($&quot;{nameof(employees)} is null or empty.&quot;, nameof(employees));

        using (var session = m_SessionFactory.OpenSession())
        {
            foreach (var employee in employees)
                session.Save(employee);
            session.Flush();
        }
    }
}
</code></pre>

<h2 id="repodb">RepoDb<a class="headerlink" href="#repodb" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public class RowCountScenario : BaseRepository&lt;EmployeeSimple, SqlConnection&gt;,
    IRowCountScenario&lt;EmployeeSimple&gt;
{
    public RowCountScenario(string connectionString)
        : base(connectionString, RDB.Enumerations.ConnectionPersistency.Instance)
    { }

    public int EmployeeCount(string lastName)
    {
        return (int)Count(e =&gt; e.LastName == lastName);
    }

    public int EmployeeCount()
    {
        return (int)CountAll();
    }

    public void InsertBatch(IList&lt;EmployeeSimple&gt; employees)
    {
        if (employees == null || employees.Count == 0)
            throw new ArgumentException($&quot;{nameof(employees)} is null or empty.&quot;, nameof(employees));

        InsertAll(employees);
    }
}
</code></pre>

<h2 id="servicestack">ServiceStack<a class="headerlink" href="#servicestack" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public class RowCountScenario : IRowCountScenario&lt;Employee&gt;
{
    private IDbConnectionFactory _dbConnectionFactory;

    public RowCountScenario(IDbConnectionFactory dbConnectionFactory)
    {
        this._dbConnectionFactory = dbConnectionFactory;
    }

    public int EmployeeCount(string lastName)
    {
        using (var db = _dbConnectionFactory.OpenDbConnection())
        {
            return (int) db.Count&lt;Employee&gt;(e =&gt; e.LastName == lastName);
        }
    }

    public int EmployeeCount()
    {
        using (var db = _dbConnectionFactory.OpenDbConnection())
        {
            return (int) db.Count&lt;Employee&gt;();
        }
    }

    public void InsertBatch(IList&lt;Employee&gt; employees)
    {
        using (var db = _dbConnectionFactory.OpenDbConnection())
        {
            db.InsertAll(employees);
        }
    }
}
</code></pre>


                    </div>
                </div>
                <footer>
                    <hr />
                    <div role="contentinfo">
The ORM Cookbook. <a href='https://github.com/Grauenwolf/DotNet-ORM-Cookbook' target='_blank'>Visit us at GitHub</a>.
                    </div>
                </footer>
            </div>
        </section>
    </div>
    <script src="js/jquery-2.1.1.min.js"></script>
    <script src="js/modernizr-2.8.3.min.js"></script>
    <script src="js/highlight.pack.js"></script>
    <script src="js/theme.js"></script>

</body>
</html>
